package top.kaoshanji.p2ch11a;

import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * author kaoshanji
 * ^_^
 * create time 2025/2/13 16:33
 */
public class OptionalMain {

    // 代码清单-p2ch11a-243页a：null-安全的第一次尝试：深层质疑
    public String getCarInsuranceNameNullSafeV1(PersonV1 person) {
        if (person != null) {
            CarV1 car = person.getCar();
            if (car != null) {
                Insurance insurance = car.getInsurance();
                if (insurance != null) {
                    return insurance.getName();
                }
            }

        }
        return "Unknown";
    }

    // 代码清单-p2ch11a-244页a：null-安全的第二种尝试：过多的退出语句
    public String getCarInsuranceNameNullSafeV2(PersonV1 person) {
        if (person == null) {
            return "Unknown";
        }

        CarV1 car = person.getCar();
        if (car == null) {
            return "Unknown";
        }

        Insurance insurance = car.getInsurance();
        if (insurance == null) {
            return "Unknown";
        }

        return insurance.getName();
    }

    // 代码清单-p2ch11a-251页a：使用Optional获取car的insurance名称
    public String getCarInsuranceName(Optional<Person> person) {
        return person.flatMap(Person::getCar)
                .flatMap(Car::getInsurance)
                .map(Insurance::getName)
                .orElse("Unknown");

    }

    // 代码清单-p2ch11a-253页a：找出person列表所使用的保险公司名称（不含重复项）
    public Set<String> getCarInsuranceNames(List<Person> peoples) {
        return peoples.stream()
                .map(Person::getCar)
                .map(optCar -> optCar.flatMap(Car::getInsurance))
                .map(optInsurance -> optInsurance.map(Insurance::getName))
                .flatMap(Optional::stream)
                .collect(Collectors.toSet());
    }


    // 代码清单-p2ch11a-256页a：两个Optional对象的组合第一个版本
    public Optional<Insurance> nullSafeFindCheapestInsurance(Optional<Person> person, Optional<Car> car) {
        if (person.isPresent() && car.isPresent()) {
            return Optional.of(findCheapestInsurance(person.get(), car.get()));
        } else {
            return Optional.empty();
        }
    }

    // 代码清单-p2ch11a-256页b：两个Optional对象的组合第二个版本
    public Optional<Insurance> nullSafeFindCheapestInsuranceQuiz(Optional<Person> person, Optional<Car> car) {
        return person.flatMap(p -> car.map(c -> findCheapestInsurance(p, c)));
    }


    public Insurance findCheapestInsurance(Person person, Car car) {
        Insurance cheapestCompany = new Insurance();
        return cheapestCompany;
    }

    // 代码清单-p2ch11a-257页a：对Optional对象进行过滤
    public String getCarInsuranceName(Optional<Person> person, int minAge) {
        return person.filter(p -> p.getAge() >= minAge)
                .flatMap(Person::getCar)
                .flatMap(Car::getInsurance)
                .map(Insurance::getName)
                .orElse("Unknown");
    }



}
